package algorithm.sorting;

import java.util.Arrays;

/**
 * 快排
 */
public class QuickSort2 {
    public static void main(String[] args) {
        int[] arr = {38,26,97,19,66,1,5,49,1,2,3};
        quickSort(arr,0, arr.length-1);
        System.out.println(Arrays.toString(arr));
    }

    public static void quickSort(int[] arr, int left, int right) {
        int l = left;
        int r = right;
        int pivot = arr[(left+right)/2];
        System.out.println("基准："+pivot);
        int temp = 0;

        while( l < r ) {
            while (arr[l] < pivot) {
                l += 1; //右移
            }
            while (arr[r] > pivot){
                r -= 1;//左移
            }

            if (l >= r) {
                break;
            }
            //交换
            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
            //交换完成后，r--，迁移
            if( arr[l] == pivot) {
                r-=1;
            }
            //交换完成后，l++,后移
            if( arr[r] == pivot) {
                l+=1;
            }
        }
        //如果l=r,必须l++,r--,否则栈溢出
        if (l == r) {
            l +=1;
            r -=1;
        }
        //递归处理,向左递归
        if (left < r) {
            quickSort(arr,left,r);
        }
        if (right > l) {
            quickSort(arr,l,right);
        }
    }
}
